using System.Text;
using Devonline.AspNetCore;
using Devonline.Logging;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.Host.AddLogging();

var services = builder.Services;
services.AddControllers();
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.AddLogging();
services.AddHttpLogging(options => options = new HttpLoggingSetting());
services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
services.AddAuthentication(BearerTokenDefaults.AuthenticationScheme)
    .AddJwtBearer(BearerTokenDefaults.AuthenticationScheme,
    options => options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = "gateway",
        ValidAudience = "foreignTrade",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("devonlinededevonlinedevonlinevonline"))
    });
services.AddAuthorization(options =>
{
    options.AddPolicy("auth", policy => policy.RequireAuthenticatedUser());
    options.AddPolicy("foreignTrade-dms", policy => policy.RequireAuthenticatedUser());
    options.DefaultPolicy = new AuthorizationPolicyBuilder(BearerTokenDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build();
    options.FallbackPolicy = new AuthorizationPolicyBuilder(BearerTokenDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build();
});

var app = builder.Build();
app.MapDefaultEndpoints();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpLogging();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapReverseProxy();
app.Run();
